import { getPrescriptionUrl, likeDoctor } from '@/services/consult'
import type { BtnType, LikeConfig } from '@/types/consult'
import dayjs from 'dayjs'
import {
  showFailToast,
  showImagePreview,
  showSuccessToast,
  type FormInstance
} from 'vant'
import { onUnmounted, ref, type Ref } from 'vue'
import { timeOptions, illnessedOptions, logisticsStatus } from '@/common'
import { cancelOrder, delOrder } from '@/services/consult'
import { sendCodeAPI } from '@/services/login'
import type { CodeType } from '@/types/service'
// hook函数，组合API函数逻辑复用
export const useLike = (params: LikeConfig) => {
  const loading = ref(false)
  const changeLike = async (item: BtnType) => {
    // 发送请求，执行关注操作
    loading.value = true
    try {
      await likeDoctor(params)
      // 修改状态
      item.likeFlag = item.likeFlag === 0 ? 1 : 0
    } finally {
      loading.value = false
    }
  }
  return { loading, changeLike }
}
// 查看处方信息
export const useShowPrescription = () => {
  const showPrescription = async (id?: string) => {
    if (id) {
      const { data } = await getPrescriptionUrl(id)
      showImagePreview([data.url])
    }
  }
  return { showPrescription }
}
// 格式转换
export const useFormat = () => {
  // 进行数据的转换 --- 患病时间和是否就诊过，vue3中没有过滤器，可以使用函数
  const getIllnessTime = (val?: number) => {
    return timeOptions.find((item) => item.value === val)?.label
  }
  const getIllnessFlag = (val?: number) => {
    return illnessedOptions.find((item) => item.value === val)?.label
  }
  // 格式化时间 -- 创建订单时间 HH:ss
  const formatTime = (time: string) => {
    return dayjs(time).format('HH:ss')
  }
  const formatTel = (tel?: string) => {
    if (tel) {
      return tel.replace(/(\d{3})\d*(\d{4})/, '$1****$2')
    }
  }
  // 转换物流信息
  const formatlogistics = (val?: number) => {
    return logisticsStatus.find((item) => item.value === val)?.label
  }
  return {
    getIllnessTime,
    getIllnessFlag,
    formatTime,
    formatTel,
    formatlogistics
  }
}
// 操作订单按钮
export const useOpeBtn = () => {
  // 删除订单 | 取消问诊
  const opeLoading = ref(false)
  const orderbtn = async (str: 'del' | 'cancel', id?: string) => {
    if (id) {
      opeLoading.value = true
      const ope = str === 'del' ? delOrder : cancelOrder
      ope(id)
        .then(() => {
          showSuccessToast(`${str === 'del' ? '删除' : '取消'}订单成功`)
        })
        .catch(() => {
          showFailToast(`${str === 'del' ? '删除' : '取消'}订单成功`)
        })
        .finally(() => {
          opeLoading.value = false
        })
    }
  }
  return { opeLoading, orderbtn }
}
// 发送验证码
export const useCodeLogin = (mobile: Ref<string>, type: CodeType) => {
  const form = ref<FormInstance | null>(null)
  const time = ref(0)
  let timer: number
  const sendCode = async () => {
    console.log(mobile)
    // 需要先进行判断，当前是否有定时器开启
    if (time.value > 0) return
    // 使用form表单的validate方法
    await form.value?.validate('mobile')
    // 校验成功，发送验证码，调用请求API函数
    await sendCodeAPI(mobile.value, type)
    // 发送验证码成功之后，需要显示倒计时的功能  --- 60s
    showSuccessToast('发送成功')
    time.value = 60
    // 需要先判断当前是否有定时器，如果有，需要先进行清除
    if (timer) clearInterval(timer)
    timer = window.setInterval(() => {
      // 进行倒计时
      time.value--
      // 如果time<=0,则需要清除定时器，并且将time复原
      if (time.value <= 0) clearInterval(timer)
    }, 1000)
  }
  // 组件移除时，需要清除定时器
  onUnmounted(() => {
    clearInterval(timer)
  })
  return { sendCode, time, form }
}
